package com.api.oa.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.api.oa.model.entity.FileList;
import com.api.oa.services.IFileService;
import com.api.shopapi.controller.BaseController;
import com.api.shopapi.entity.MyResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    @Autowired
    private IFileService iFileService;


    @RequestMapping("/upload")
    public MyResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("uid") String uid) throws IllegalStateException {
        try {
            File root = new File(this.filesRootPath, DateUtil.format(new Date(),"yyyy-MM"));
            String shuffix = FilenameUtils.getExtension(file.getOriginalFilename());
            String newFileName = IdUtil.simpleUUID() + "." + shuffix;
            File targetFile = new File(root, newFileName);
            FileUtil.touch(targetFile);
            file.transferTo(targetFile);
            FileList filelist = new FileList();
            String filename = file.getOriginalFilename();
            filelist.setFileName(filename);
            filelist.setFilePath(targetFile.getAbsolutePath().replace("\\", "/").replace(this.filesRootPath, ""));
            filelist.setFileShuffix(shuffix);
            filelist.setSize(file.getSize());
            filelist.setUploadTime(new Date());
            filelist.setContentType(file.getContentType());
            filelist.setFileUserId(uid);
            filelist.setFileClassify(type(filelist.getContentType()));
             iFileService.add(filelist);
            return success(filelist);
        }catch (Exception e){
            e.printStackTrace();
             return anomalous(e.getMessage());
        }
    }

    private int type(String contentType){
        String[] types = new String[]{"image","application","audio","video","other"};
        for (int i = 0; i < types.length; i++) {
            if(contentType.startsWith(types[i])){
                return i;
            }
        }
        return 4;
    }


    @RequestMapping(value = "/down/{id}", method = RequestMethod.GET)
    public MyResult download(@PathVariable Long id, HttpServletResponse res) {
        try {
            FileList one = iFileService.one(id);
            if(one == null) failed("未找到文件");
            res.addHeader("Content-Disposition", "attachment;filename=" + new String(one.getFileName().getBytes(StandardCharsets.UTF_8),"ISO8859_1"));
            res.getOutputStream().write(FileUtil.readBytes(one.getFilePath()));
            return success("删除成功!");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }








    @RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
    public MyResult remove(@PathVariable Long id) {
        try {
            iFileService.remove(id);
            return success("删除成功!");
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }

    }





    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MyResult list(@RequestParam(defaultValue = "") Long classify,@RequestParam(defaultValue = "") String uid,@RequestParam(defaultValue = "") String keyWord,@RequestParam Integer pageIndex,@RequestParam Integer pageSize) {
        try {
            return success(iFileService.list(StrUtil.isBlankIfStr(classify) ? null : classify, uid, keyWord,pageIndex,pageSize));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
    public MyResult one(@PathVariable Long id) {
        try {
            return success(id == null ? null : iFileService.one(id));
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }



    @RequestMapping(value = "/download/apk", method = RequestMethod.GET)
    public void one(HttpServletResponse res) {
        try {
            res.addHeader("Content-Disposition", "attachment;filename=" + new String("base".getBytes(StandardCharsets.UTF_8),"ISO8859_1"));
            res.getOutputStream().write(FileUtil.readBytes(rootPath + "/base.apk"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
